import { forwardRef, useImperativeHandle, useRef, useState } from 'react';

import { useRequest } from 'ahooks';
import {
  Button,
  DatePicker,
  Drawer,
  Form,
  FormProps,
  Input,
  InputNumber,
  Space,
  TreeSelect
} from 'antd';
import { DataNode } from 'antd/es/tree';
import dayjs from 'dayjs';

import { store } from '@/store';

import { orgDeptInfoTreeList } from '@/services/base/bumenguanlibumenxiangguanjiekou';
import { orgUserInfoVoPage } from '@/services/base/yonghuguanlixitongyonghujiekou';
import {
  safeEquipmentInventoryAdd,
  safeEquipmentInventoryUpdate
} from '@/services/bizApi/anquanqicaixinxiguanlibiaojiekou';
import { findIdByName } from '@/utils';
import { ProFormSelect } from '@ant-design/pro-form';

import { BizObject } from './';

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EditRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'add';
        })
      | (EditOpenBaseArgs & {
          type: 'edit';
          rowData: BizObject;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          rowData: BizObject;
        })
  ) => void;
};

export type EditProps = {};

const Edit: React.ForwardRefRenderFunction<EditRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditRef['open']>[0]>();
  const treeDict = useRef<Record<number, DataNode>>({});
  const tree = useRequest(async () => {
    treeDict.current = {};

    const res = await orgDeptInfoTreeList();

    const formatData = (data: BASE.OrgDeptInfoVo[]): DataNode[] => {
      const result: DataNode[] = [];

      data.forEach((item) => {
        const node: DataNode = {
          title: item.deptName,
          key: item.id!,
          // @ts-ignore
          value: item.id!,
          children: []
        };

        treeDict.current[item.id!] = node;

        if (item.child && item.child.length > 0) {
          node.children = formatData(item.child);
        }

        result.push(node);
      });

      return result;
    };

    return formatData(res.data || []);
  });

  const userInfo = useRequest(
    async () => {
      const res = await orgUserInfoVoPage({ page: 1, size: 1000 });

      return res?.data?.records;
    },
    {
      refreshDeps: []
    }
  );

  const submit = useRequest(
    async ({ _type, ...values }) => {
      const query = {
        ...values,
        usingDeptName: findIdByName(tree?.data || [], values?.usingDeptId as unknown as string),
        userName: userInfo?.data?.filter((item) => item.id === values?.userId)?.[0]?.fullName,
        productionDate: values?.productionDate
          ? dayjs(values?.productionDate).format('YYYY-MM-DD')
          : undefined,
        purchaseDate: values?.purchaseDate
          ? dayjs(values?.purchaseDate).format('YYYY-MM-DD')
          : undefined,
        lastMaintenanceDate: values?.lastMaintenanceDate
          ? dayjs(values?.lastMaintenanceDate).format('YYYY-MM-DD')
          : undefined
      };

      if (args?.type === 'edit' && args.rowData) {
        query.id = args.rowData.id;
      }

      await (args?.type === 'edit'
        ? safeEquipmentInventoryUpdate(query)
        : safeEquipmentInventoryAdd(query));

      args?.onSuccess?.();
      setOpen(false);

      store.app?.message.success(args?.type === 'edit' ? '编辑成功' : '新增成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);

        setTimeout(() => {
          // 编辑回填数据
          if ((arg?.type === 'edit' || arg?.type === 'detail') && arg?.rowData) {
            // 回填数据
            form.setFieldsValue({
              ...arg.rowData,
              productionDate: arg.rowData?.productionDate
                ? dayjs(arg.rowData?.productionDate)
                : undefined,
              purchaseDate: arg.rowData?.purchaseDate
                ? dayjs(arg.rowData?.purchaseDate)
                : undefined,
              lastMaintenanceDate: arg.rowData?.lastMaintenanceDate
                ? dayjs(arg.rowData?.lastMaintenanceDate)
                : undefined
            });
          } else {
            form.resetFields();
          }
        });
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');

      return;
    }

    setOpen(false);
  };

  // 仅保存
  const onSave = () => {
    form.submit();
  };

  return (
    <Drawer
      title={
        {
          add: '新增',
          edit: '编辑',
          detail: '详情'
        }[args?.type as string]
      }
      extra={
        <>
          {args?.type !== 'detail' && (
            <Space>
              <Button
                type="primary"
                loading={submit.loading}
                disabled={submit.loading}
                onClick={onSave}
              >
                保存
              </Button>
              <Button onClick={onCancel} disabled={submit.loading}>
                取消
              </Button>
            </Space>
          )}
        </>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        disabled={args?.type === 'detail'}
        requiredMark={args?.type !== 'detail'}
        variant={args?.type === 'detail' ? 'borderless' : undefined}
      >
        <Form.Item
          label="器材编号"
          name="equipmentCode"
          rules={[
            {
              required: true,
              message: '请输入器材编号'
            }
          ]}
        >
          <Input placeholder="请输入器材编号" />
        </Form.Item>
        <Form.Item
          label="器材名称"
          name="equipmentName"
          rules={[
            {
              required: true,
              message: '请输入器材名称'
            }
          ]}
        >
          <Input placeholder="请输入器材名称" />
        </Form.Item>
        <Form.Item
          label="器材类型"
          name="equipmentType"
          rules={[
            {
              required: false,
              message: '请输入器材类型'
            }
          ]}
        >
          <Input placeholder="请输入器材类型" />
        </Form.Item>
        <Form.Item
          label="规格型号"
          name="specificationModel"
          rules={[
            {
              required: false,
              message: '请输入规格型号'
            }
          ]}
        >
          <Input placeholder="请输入规格型号" />
        </Form.Item>
        <Form.Item
          label="生产日期"
          name="productionDate"
          rules={[
            {
              required: false,
              message: '请选择生产日期'
            }
          ]}
        >
          <DatePicker placeholder="请选择生产日期" style={{ width: '100%' }} />
        </Form.Item>
        <Form.Item
          label="采购日期"
          name="purchaseDate"
          rules={[
            {
              required: false,
              message: '请选择采购日期'
            }
          ]}
        >
          <DatePicker placeholder="请选择采购日期" style={{ width: '100%' }} />
        </Form.Item>
        <Form.Item
          label="采购价格"
          name="purchasePrice"
          rules={[
            {
              required: false,
              message: '请输入采购价格'
            }
          ]}
        >
          <InputNumber min={0} placeholder="请输入采购价格" style={{ width: '100%' }} />
        </Form.Item>
        <Form.Item
          label="使用部门"
          name="usingDeptId"
          rules={[
            {
              required: true,
              message: '请选择使用部门'
            }
          ]}
        >
          <TreeSelect
            treeData={tree.data}
            treeNodeFilterProp="title"
            showSearch
            placeholder="请选择使用部门"
            allowClear
          />
        </Form.Item>
        <ProFormSelect
          name="userId"
          label="使用人"
          placeholder="请选择使用人"
          dependencies={['usingDeptId']}
          showSearch={true}
          rules={[{ required: true, message: '请选择使用人' }]}
          request={async ({ usingDeptId }) => {
            const res = await orgUserInfoVoPage({ page: 1, size: 1000, deptId: usingDeptId });
            return (
              res?.data?.records?.map((item) => {
                return {
                  label: item?.fullName,
                  value: item?.id
                };
              }) || []
            );
          }}
        />
        <Form.Item
          label="上次维修日期"
          name="lastMaintenanceDate"
          rules={[
            {
              required: false,
              message: '请选择上次维修日期'
            }
          ]}
        >
          <DatePicker placeholder="请选择上次维修日期" style={{ width: '100%' }} />
        </Form.Item>
        <Form.Item
          label="存放地点"
          name="storageLocation"
          rules={[
            {
              required: false,
              message: '请输入存放地点'
            }
          ]}
        >
          <Input placeholder="请输入存放地点" />
        </Form.Item>
        <Form.Item
          label="库存数量"
          name="inventoryQuantity"
          rules={[
            {
              required: false,
              message: '请输入库存数量'
            }
          ]}
        >
          <InputNumber min={0} placeholder="请输入库存数量" style={{ width: '100%' }} />
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default forwardRef(Edit);
